Page({
  data: {
    commandSent: false ,// 用于标记命令是否已发送
    deviceStatus: '未知',
    Status : 0,
    temperature: '25',
    humidity: '30',
    temperature_min: 15,
    temperature_max: 40,
    humidity_min: 30,
    humidity_max: 80,
    light: 50,
    dan_int: 0,
    jia_int: 0,
    lin_int: 0,
    tu_int: 0,
    uid:"3abe53a395db46d386c1acec6028aa7e",//用户密钥，巴法云控制台获取
    myTopic:"abiboca123",//图片上传的主题，图片云控制台创建
    topic: "light002",//巴法云下发命令esp32
    num:1,      //获取的图片数量，可随意
    imgList:[], //存储图片地址和时间，用于前端展示
    picArr:[], //存储图片的地址，用于图片点击预览
  },

  onLoad: function() {
    this.sendCommand("0");
    this.startFetchingData();
  },
  
  sendCommand: function(abc){
    const authInfo = "version=2018-10-31&res=products%2Fh5LSf4tTEy%2Fdevices%2Ftest&et=2052911776&method=md5&sign=Jd%2FlR%2BJti5hBm4mIklN49Q%3D%3D";
    const commandData = {
      "product_id": "h5LSf4tTEy",
      "device_name": "test",
      "params": {
        "String":abc.toString() // 假设您要设置的命令参数
      }
    };

    wx.request({
       url: 'https://iot-api.heclouds.com/thingmodel/set-device-property', // 确保URL正确
       method: 'POST',
       header: {
         'Authorization': authInfo,
         'Content-Type': 'application/json'
       },
       data: JSON.stringify(commandData),
       success: (res) => {
         if (res.data.code === 0) {
           this.setData({
             commandSent: true
           });
           console.log('Command sent successfully:', res.data.data);
           if(res.data.msg === "succ"){
            this.setData({
              deviceStatus: '在线' ,              
            });
              this.Status=1;
          }
           wx.showToast({
             title: '命令发送成功',
             icon: 'success'
           });
         } else {
           console.log('Failed to send command:', res.data.msg);
           this.setData({
            deviceStatus: '离线' ,              
          });
            this.Status=0;
            wx.showToast({
             title: '设备离线',
             icon: 'none'
            });     
         }
       },
       fail: (err) => {
         console.error('Request failed:', err);
         wx.showToast({
             title: '请求失败，请检查网络后重试',
             icon: 'none'
         });
       }
     });
  },

//获取温湿度
gethumi_temp: function(){
  const authInfo = "version=2018-10-31&res=products%2Fh5LSf4tTEy%2Fdevices%2Ftest&et=2052911776&method=md5&sign=Jd%2FlR%2BJti5hBm4mIklN49Q%3D%3D";
  wx.request({
    url: 'https://iot-api.heclouds.com/thingmodel/query-device-property?product_id=h5LSf4tTEy&device_name=test',
    method: 'GET',
    header: {
      'Authorization': authInfo,
      'Content-Type': 'application/json'
    },
    success: (res) => {
      // 检查响应是否成功
      if (res.data.code === 0 && res.data.msg === "succ" && res.data.data) {
        if (Array.isArray(res.data.data)) {
          const dataList = res.data.data;
          // 初始化温度和湿度变量
          let temper = null;
          let humid = null;
          let temper1 = null;
          let humid1 = null;
          let temper2 = null;
          let humid2 = null;
          let light1 =null;
          let dan =null;
          let jia =null;
          let lin =null;
          let tu =null;
          // 遍历数据列表，查找温度和湿度
          dataList.forEach(item => {
            if (item.identifier === "temp") {
              temper = item.value;
            } else if (item.identifier === "humi") {
              humid = item.value;
            }else if (item.identifier === "tmin") {
              temper1 = item.value;
              temper1 = parseInt(temper1);
            }else if (item.identifier === "tmax") {
              temper2 = item.value;
              temper2 = parseInt(temper2);
            }else if (item.identifier === "hmin") {
              humid1 = item.value;
              humid1 = parseInt(humid1);
            }else if (item.identifier === "hmax") {
              humid2 = item.value;
              humid2 = parseInt(humid2);
            }else if (item.identifier === "light") {
              light1 = item.value;
              light1 = parseInt(light1);
            }else if (item.identifier === "dan") {
              dan = item.value;
              dan = parseInt(dan);
            }else if (item.identifier === "jia") {
              jia = item.value;
              jia = parseInt(jia);
            }else if (item.identifier === "lin") {
              lin = item.value;
              lin = parseInt(lin);
            }else if (item.identifier === "tu") {
              tu = item.value;
              tu = parseInt(tu);
            }
          });
          // 返回温度和湿度
          if (temper !== null && humid !== null) {
            console.log(`温度: ${temper},范围:${temper1}~ ${temper2};湿度: ${humid},范围:${humid1}~ ${humid2},;光强: ${light1}`);
            // 这里可以进一步处理温度和湿度数据，例如更新页面显示
            this.setData({
              temperature: temper,
              humidity: humid,
              temperature_min: temper1,
              temperature_max: temper2,
              humidity_min: humid1,
              humidity_max: humid2,
              light: light1,
              dan_int: dan,
              jia_int: jia,
              lin_int: lin,
              tu_int: tu,
            });

          } else {
            console.log("未找到温度或湿度数据");
          }
        } else {
          // 数据格式不正确
          console.error("Data format is incorrect:", res.data);
        }
      } else {
        // 响应不成功
        console.error("Failed to extract temperature and humidity:", res.data);
      }
    },
    fail: (err) => {
      // 请求失败处理
      console.error("请求失败:", err);
    }
  });
},

led13_open: function(){
  this.sendCommand("1"); 
 },
 led13_close: function(){
  this.sendCommand("0"); 
 }, 

add1: function()
{
  this.sendCommand("6");
  if(this.Status === 1){
  this.setData({
    temperature_min: this.data.temperature_min + 1
  });}
},
add2: function()
{
  this.sendCommand("8");
  if(this.Status === 1){
    this.setData({
      temperature_max: this.data.temperature_max + 1
    });}
},
add3: function()
{
  this.sendCommand("2");
  if(this.Status === 1){
    this.setData({
      humidity_min: this.data.humidity_min + 2
    });}
},
add4: function()
{
  this.sendCommand("4");
  if(this.Status === 1){
    this.setData({
      humidity_max: this.data.humidity_max + 2
    });}
},
sub1: function()
{
  this.sendCommand("7");
  if(this.Status === 1){
    this.setData({
      temperature_min: this.data.temperature_min - 1
    });}
},
sub2: function()
{
  this.sendCommand("9");
  if(this.Status === 1){
    this.setData({
      temperature_max: this.data.temperature_max - 1
    });}
},
sub3: function()
{
  if(this.Status === 1){
    this.setData({
      humidity_min: this.data.humidity_min - 2
    });}
},
sub4: function()
{
  this.sendCommand("5");
  if(this.Status === 1){
    this.setData({
      humidity_max: this.data.humidity_max - 2
    });}
},

getPicture(){    //获取图片函数
  //api 接口详细说明见巴法云接入文档
  var that = this
  wx.request({
    url: 'https://images.bemfa.com/cloud/v1/get/', //获取图片接口，详见巴法云接入文档
    data: {
      uid: that.data.uid,       //uid字段
      topic: that.data.myTopic,//topic字段
      num:that.data.num        //num字段
    },
    header: {
      'content-type': "application/x-www-form-urlencoded"
    },
    success (res) {
       console.log(res)     //打印获取结果
       var imgArr = []      //定义空数组，用于临时存储图片地址和时间
       var arr = []         //定义空数组，用于临时存储图片地址
       for(var i = 0;i<res.data.data.length;i++){//遍历获取的结果数组
         var url = res.data.data[i].url          //提取图片地址
         var time = that.time(url.substring(url.lastIndexOf("-")+1,url.lastIndexOf(".")))//提取图时间
         imgArr.push({"url":url,"time":time})    //将存储图片地址和时间存入临时数组
         arr.push(url)                           //将存储图片地址存入临时数组
       }
       
       that.setData({     //把临时数组值复制给变量用于展示
         imgList:imgArr, //将临时存储图片地址和图片时间的数组赋值给用于图片预览的数组
         picArr:arr,    //将临时存储图片地址的数组赋值给用于图片预览的数组
       })
      console.log(that.data.imgList)   //打印赋值结果
    }
  })

},
clickImg(e){                      //点击预览函数
    console.log(e.currentTarget.dataset.index)    //打印数组索引值
    var nowIndex = e.currentTarget.dataset.index  //获取索引值
    wx.previewImage({           //图片预览接口
      current: this.data.picArr[nowIndex],//当前图片地址
      urls: this.data.picArr    //图片地址数组
    })
},
time(time) {                    //时间戳转时间函数
  var date = new Date(parseInt(time)*1000 + 8 * 3600 * 1000);
  return date.toJSON().substr(0, 19).replace('T', ' ');
},

openclick: function() {
    //控制接口
    var that = this;
    wx.request({
      url: 'https://api.bemfa.com/api/device/v1/data/1/', //api接口，详见接入文档
      method:"POST",
      data: {  //请求字段，详见巴法云接入文档，http接口
        uid: that.data.uid,
        topic: that.data.topic,
        msg:"on"   //发送消息为on的消息
      },
      header: {
        'content-type': "application/x-www-form-urlencoded"
      },
      success (res) {
        console.log(res.data)
        wx.showToast({
          title:'采集成功',
          icon:'success',
          duration:1000
        })
      }
    })
},

startFetchingData: function() {
  this.gethumi_temp(); // 立即执行一次
  this.getPicture();
  this.intervalHumiTemp = setInterval(this.gethumi_temp, 20000); // 每分钟执行一次
  this.intervalPicture = setInterval(this.getPicture, 20000); // 每分钟执行一次
},
onUnload: function() {
  // 页面卸载时清除定时器
  if (this.interval) {
    clearInterval(this.intervalHumiTemp);
    clearInterval(this.intervalPicture);
  }
}
});